package com.lidsu.gulimall.product.web;

import com.alibaba.fastjson.JSON;
import com.lidsu.gulimall.product.entity.CategoryEntity;
import com.lidsu.gulimall.product.service.CategoryService;
import com.lidsu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.ws.RequestWrapper;
import javax.xml.ws.soap.Addressing;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {
        //查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Category();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catelog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogJson();
        System.out.println(JSON.toJSONString(catelogJson));
        return catelogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1.获取一把锁       只要锁名一样，就是一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
        lock.lock();//阻塞式等待
        try {
            System.out.println("加锁成功。。执行业务" + Thread.currentThread().getId());
            Thread.sleep(300);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3.解锁
            System.out.println("释放锁" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

}
